from django.shortcuts import render, redirect, reverse
from task_market.models import Task, Taskdata, DataUpload, TaskApplication, Check_result
from user_mng.models import users
from django.contrib import messages
import datetime
from django.utils import timezone
from django.db.models import Sum, Avg, Q


# Create your views here.
def base(request):
    return render(request, 'base_fq.html')


def index(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    item = request.GET.get('search')
    if not request.session.get('account'):
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]  # name
        typee = user_list[request.session.get('account')][1]  # user_type
    if not item:
        task_list = Task.objects.exclude(Q(task_status=3) | Q(task_status=0))[:5]
        return render(request, 'task_market/index.html',
                      {'tasks': task_list, 'name': name, 'staues': staue, 'type': typee})
    else:
        task_list = Task.objects.filter(task_name__icontains=item)
        return render(request, 'task_market/all_grid.html',
                      {'tasks': task_list, 'name': name, 'staues': staue, 'type': typee})


def details(request, id):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'
    user_list = {i.user_account: [i.user_name, i.user_type, i.user_id] for i in users.objects.all()}
    if not request.session.get("account"):
        name = '请登录'
    else:
        name = user_list[request.session.get('account')][0]  # name
    assign_data_all = Taskdata.objects.filter(taskdata_task_id=id).count()
    assign_data_anno = Taskdata.objects.filter(taskdata_task_id=id,
                                               taskdata_status='1').count()
    # print(type(assign_data_all))
    perc_anno = str(assign_data_anno / assign_data_all * 100)[:5] + '%'
    item = request.GET.get('search')
    if not item:
        content_list = Taskdata.objects.all()
        task_list = Task.objects.all()
        content_detail = []
        for content in content_list:  # 找到该任务的所有内容
            if id == int(content.taskdata_task_id):
                content_detail.append(content)
        # print(content_detail)
        for task in task_list:
            if id == task.id:
                task_detail = task  # 找到该单个任务的信息
        if not request.session.get('account'):
            return redirect('task_market:unaccessible')
        elif user_list[request.session.get('account')][1] == 1:
            return render(request, 'task_market/task_details_tagger.html',
                          {'content_details': content_detail, 'task_details': task_detail, 'name': name,
                           'staues': staue, 'all_assign_num': assign_data_all,
                           'anno_assign_num': assign_data_anno,
                           'perc_anno': perc_anno})
        elif user_list[request.session.get('account')][1] == 2:
            return render(request, 'task_market/task_details_publisher.html',
                          {'content_details': content_detail, 'task_details': task_detail, 'name': name,
                           'staues': staue, 'all_assign_num': assign_data_all,
                           'anno_assign_num': assign_data_anno,
                           'perc_anno': perc_anno})
    else:
        task_list = Task.objects.filter(task_name__icontains=item)
        return render(request, 'task_market/all_grid.html', {'tasks': task_list, 'name': name, 'staues': staue})


def all_grid(request):
    user_list = {i.user_account: [i.user_name, i.user_type] for i in users.objects.all()}
    if not request.session.get('account'):  # 判断是否登录 显示不同按键
        staue = 'login'
        name = '请登录'
        typee = '1209'
    else:
        staue = 'logout'
        name = user_list[request.session.get('account')][0]
        typee = user_list[request.session.get('account')][1]
    item = request.GET.get('search')
    if not item:
        task_list = Task.objects.filter(task_status=1)
    else:
        task_list = Task.objects.filter(task_status=1).filter(task_name__icontains=item)
    # if request.POST.get('sort') == 'ID':
    return render(request, 'task_market/all_grid.html',
                  {'tasks': task_list, 'name': name, 'staues': staue, 'type': typee})


def all_list(request):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'
    user_list = {i.user_account: i.user_name for i in users.objects.all()}
    if not request.session.get("account"):
        name = '请登录'
    else:
        name = user_list[request.session.get('account')]
    item = request.GET.get('search')
    if not item:
        task_list = Task.objects.all()
        return render(request, 'task_market/all_list.html', {'tasks': task_list, 'name': name, 'staues': staue})
    else:
        task_list = Task.objects.filter(task_name__icontains=item)
        return render(request, 'task_market/all_list.html', {'tasks': task_list, 'name': name, 'staues': staue})


def unaccessible(request):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'
    user_list = {i.user_account: i.user_name for i in users.objects.all()}
    if not request.session.get("account"):
        name = '请登录'
    else:
        name = user_list[request.session.get('account')]
    item = request.GET.get('search')
    if not item:
        return render(request, 'task_market/unaccessible.html', {'name': name, 'staues': staue})
    else:
        task_list = Task.objects.filter(task_name__icontains=item)
        return render(request, 'task_market/all_grid.html', {'tasks': task_list, 'name': name, 'staues': staue})


def task_apply(request, task_id):
    if not request.session.get('account'):
        staue = 'login'
    else:
        staue = 'logout'
    user_list = {i.user_account: [i.user_name, i.user_id] for i in users.objects.all()}
    if not request.session.get("account"):
        name = '请登录'
    else:
        name = user_list[request.session.get('account')][0]
    if request.method == "POST":
        apply_volumn = request.POST.get("apply_volumn")
        print(type(user_list[request.session.get('account')][1]))
        if int(apply_volumn) > 0:
            total_volumn = Taskdata.objects.filter(
                taskdata_task_id=task_id
            ).count()
            applied_volumn = TaskApplication.objects.filter(
                Task_id=task_id
            ).aggregate(Sum("Apply_volumn"))
            remain_volumn = total_volumn - (applied_volumn["Apply_volumn__sum"] or 0)
            print(total_volumn, applied_volumn)
            if int(apply_volumn) <= remain_volumn:
                new_application = TaskApplication.objects.create(
                    Task_id=task_id,
                    Task_applier_id=user_list[request.session.get('account')][1],
                    Apply_volumn=apply_volumn,
                    Apply_time=timezone.now(),
                )
                x = Taskdata.objects.filter(taskdata_task_id=task_id)[
                    int(applied_volumn["Apply_volumn__sum"] or 0): int(applied_volumn["Apply_volumn__sum"] or 0) + int(
                        apply_volumn)]
                for task in x:
                    task.taskdata_assign = user_list[request.session.get('account')][1]
                    task.save()
                print("申请成功")
                messages.success(request, '申请成功')
            else:
                print("申请失败")
        else:
            # messages.error(request, '请输入大于0的数')
            pass

        return redirect(reverse('task_market:details', kwargs={'id': task_id}))

    item = request.GET.get('search')
    if not item:
        return render(request, "task_market/task_apply.html", {'name': name, 'staues': staue, 'task_id': task_id})
    else:
        task_list = Task.objects.filter(task_name__icontains=item)
        return render(request, 'task_market/all_grid.html', {'tasks': task_list, 'name': name, 'staues': staue})
